<template>
  <a-card :body-style="{ height: 'calc(100vh - 125px)' }">
    <!-- 数据列表 -->
    <a-row class="w-full h-full flex flex-col overflow-x-auto overflow-y-hidden">
      <!-- 查询条件 -->
      <a-row class="w-full" v-if="showSearchRow">
        <a-form :model="searchForm" layout="inline" label-align="left" size="small">
          <a-form-item field="plateNumberName" label="车牌号">
            <a-input v-model="searchForm.plateNumberName" placeholder="请输入车牌号" />
          </a-form-item>
          <a-form-item field="vehicleModel" label="车型名称">
            <a-input v-model="searchForm.vehicleModel" placeholder="请输入车型名称" />
          </a-form-item>
        </a-form>
        <a-row justify="center" class="w-full mt-2">
          <a-space>
            <a-button type="primary" @click="getPageList(false)">
              <template #icon><icon-search /></template>
              <template #default>查询</template>
            </a-button>
            <a-popconfirm
              content="确定删除选中车牌信息吗?"
              type="warning"
              :popup-visible="deleteConfirmVisible"
              @ok="onDeleteConfirmOK"
              @cancel="onDeleteConfirmCancel"
            >
              <a-button
                type="primary"
                status="danger"
                @click="deleteBtnClick(selectedKeys)"
              >
                <template #icon><icon-delete /></template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
            <a-button @click="getPageList(true)">
              <template #icon><icon-sync /></template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-row>
      </a-row>

      <!-- 分割线 -->
      <a-divider v-if="showSearchRow" class="mt-2" />

      <!-- 数据操作区 -->
      <a-row class="w-full flex justify-between">
        <a-space>
          <!-- 添加 -->
          <a-button
            v-perm="['tc:plateNumber:add']"
            type="primary"
            size="small"
            @click="addBtnClick()"
          >
            <template #icon><icon-plus /></template>
            <template #default>添加</template>
          </a-button>

          <!-- 插入车牌 -->
          <a-button
            v-perm="['tc:plateNumber:add']"
            type="primary"
            status="success"
            size="small"
            @click="insertPlateNumberClick()"
          >
            <template #icon><icon-import /></template>
            <template #default>插入车牌</template>
          </a-button>
        </a-space>

        <!-- 其他按钮 -->
        <a-space>
          <!-- 刷新 -->
          <a-button shape="circle" size="small" @click="getPageList(false)">
            <template #icon><icon-refresh /></template>
          </a-button>
          <!-- 收缩/展开 -->
          <a-button shape="circle" size="small" @click="showSearchRow = !showSearchRow">
            <template #icon>
              <icon-caret-up v-if="showSearchRow" />
              <icon-caret-down v-else />
            </template>
          </a-button>
        </a-space>
      </a-row>

      <!-- 数据展示区 -->
      <a-row class="w-full flex-1 mt-3 overflow-y-auto">
        <a-table
          class="w-[100%]"
          :scroll="{ minWidth: 600, y: '100%' }"
          :columns="datatable.columns"
          :data="datatable.records"
          :loading="datatable.loading"
          :pagination="false"
          table-layout-fixed
          row-key="plateNumberId"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
        >
          <template #plateNumberName="{ record }">
            <a-link @click="detailBtnClick(record.plateNumberId)" icon>{{
              record.plateNumberName
            }}</a-link>
          </template>
          <!-- 操作 -->
          <template #operation="{ record }">
            <a-button
              v-perm="['tc:plateNumber:update']"
              type="text"
              size="mini"
              @click="updateBtnClick(record.plateNumberId)"
            >
              <template #icon>
                <icon-edit />
              </template>
              <template #default>修改</template>
            </a-button>
            <a-popconfirm
              content="确认要删除吗?"
              @ok="deleteBtnOkClick(record.plateNumberId)"
            >
              <a-button
                v-perm="['tc:plateNumber:delete']"
                type="text"
                status="danger"
                size="mini"
              >
                <template #icon>
                  <icon-delete />
                </template>
                <template #default>删除</template>
              </a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </a-row>

      <!-- 分页 -->
      <a-row class="w-full flex justify-end mt-2">
        <pagination
          v-if="datatable.total > 0"
          v-model:page-num="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          :total="datatable.total"
          @pagination="getPageList(false)"
        />
      </a-row>
    </a-row>

    <a-modal
      v-model:visible="modal.visible"
      :esc-to-close="false"
      :mask-closable="false"
      draggable
      width="1000px"
      :footer="false"
    >
      <template #title>{{ modal.title }}</template>
      <component
        :is="modal.component"
        :params="modal.params"
        @ok="onOk"
        @cancel="onCancel"
        v-if="modal.visible"
      />
    </a-modal>

    <!-- 插入车牌弹窗 -->
    <a-modal
      v-model:visible="insertPlateNumberModal.visible"
      title="插入车牌"
      @ok="handleInsertPlateNumberOk"
      @cancel="handleInsertPlateNumberCancel"
      :confirm-loading="insertPlateNumberModal.confirmLoading"
    >
      <a-form :model="insertPlateNumberModal" layout="vertical">
        <a-form-item field="count" label="插入数量">
          <a-input-number
            v-model="insertPlateNumberModal.count"
            placeholder="请输入插入数量"
            :min="1"
            :max="100"
            style="width: 100%"
          />
        </a-form-item>
        <p>说明：系统将从订单表中获取指定数量未被识别的车牌插入到车牌表中</p>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, shallowRef } from "vue";
import {
  getPageListApi,
  deleteApi,
  getApi,
  addApi,
  updateApi,
  insertPlateNumberApi,
} from "~/api/tc/plateNumber.js";
import PlateNumberDetail from "~/pages/tc/plateNumber/PlateNumberDetail.vue";
import PlateNumberEdit from "~/pages/tc/plateNumber/PlateNumberEdit.vue";

// 全局实例
const { proxy } = getCurrentInstance();

// 是否展示搜索区域
const showSearchRow = ref(true);
// 搜索参数表单
const searchForm = reactive({
  // 车牌名称
  plateNumberName: null,
  // 车型名称
  vehicleModel: null,
  // 页码
  pageNum: 1,
  // 条数
  pageSize: 10,
});

// 插入车牌弹窗
const insertPlateNumberModal = reactive({
  visible: false,
  confirmLoading: false,
  count: 10, // 默认数量
});

// 表格选中数据
const selectedKeys = ref([]);
// 表格选中
const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: true,
  onlyCurrent: true,
});

// 数据列表
const datatable = reactive({
  // 列配置
  columns: [
    {
      title: "车牌号",
      dataIndex: "plateNumberName",
      slotName: "plateNumberName",
      align: "center",
    },
    {
      title: "车型名称",
      dataIndex: "vehicleModel",
      align: "center",
    },
    // 移除了文件URL列
    // 移除了识别结果列
    {
      title: "操作",
      slotName: "operation",
      align: "center",
      width: 160,
      fixed: "right",
    },
  ],
  // 加载
  loading: false,
  // 数据列表
  records: [],
  // 总条数
  total: 0,
});

// 查询数据列表
const getPageList = (isReset = false) => {
  if (isReset) {
    searchForm.plateNumberName = null;
    searchForm.vehicleModel = null;
    searchForm.pageNum = 1;
    searchForm.pageSize = 10;
  }

  datatable.loading = true;
  getPageListApi(searchForm)
    .then((res) => {
      datatable.records = res.records;
      datatable.total = res.total;
    })
    .finally(() => {
      datatable.loading = false;
    });
};

// 公共模态框
const modal = reactive({
  // 是否显示
  visible: false,
  // 模态框标题
  title: "车牌信息管理",
  // 宽度
  width: "50%",
  // 传递参数
  params: {},
  // 组件名称
  component: null,
});

// 添加按钮 -> 点击事件
const addBtnClick = () => {
  modal.visible = true;
  modal.title = "添加车牌信息";
  modal.width = "400px";
  modal.params = { operationType: proxy.operationType.add.type };
  modal.component = shallowRef(PlateNumberEdit);
};

// 表格行数据 "查看" -> 点击
const detailBtnClick = (plateNumberId) => {
  modal.visible = true;
  modal.title = "查看车牌信息";
  modal.params = {
    operationType: proxy.operationType.detail.type,
    plateNumberId: plateNumberId,
  };
  modal.component = shallowRef(PlateNumberDetail);
};

// 表格行数据 "修改" -> 点击
const updateBtnClick = (plateNumberId) => {
  modal.visible = true;
  modal.title = "修改车牌信息";
  modal.params = {
    operationType: proxy.operationType.update.type,
    plateNumberId: plateNumberId,
  };
  modal.component = shallowRef(PlateNumberEdit);
};

// 删除确认弹窗 -> 确认
const deleteConfirmVisible = ref(false);

// 表格行数据 "删除" -> 点击
const deleteBtnClick = (selectedKeys) => {
  if (selectedKeys.length === 0) {
    proxy.$msg.error("请选择要删除的车牌信息");
    return;
  }
  deleteConfirmVisible.value = true;
};

// 表格行数据 "删除" -> 确认
const deleteBtnOkClick = (plateNumberId) => {
  deleteApi(plateNumberId).then(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    // 刷新列表
    getPageList();
  });
};

const onDeleteConfirmCancel = () => {
  deleteConfirmVisible.value = false;
  selectedKeys.value = [];
};

// 删除确认弹窗 -> 确认
const onDeleteConfirmOK = () => {
  deleteConfirmVisible.value = false;
  let ids = [];
  selectedKeys.value.map((id) => {
    ids.push(id);
  });
  deleteApi(ids).then(() => {
    proxy.$msg.success(proxy.operationType.delete.success);
    // 刷新列表
    selectedKeys.value = [];
    getPageList();
  });
};

const onOk = () => {
  modal.visible = false;
  // 查询数据列表
  getPageList();
};

// 模态框 -> 取消
const onCancel = () => {
  modal.visible = false;
};

// 查询数据列表
getPageList();
// 插入车牌按钮点击
const insertPlateNumberClick = () => {
  insertPlateNumberModal.visible = true;
  insertPlateNumberModal.count = 10;
};

// 插入车牌确认
const handleInsertPlateNumberOk = () => {
  insertPlateNumberModal.confirmLoading = true;

  insertPlateNumberApi(insertPlateNumberModal.count)
    .then(() => {
      proxy.$msg.success("插入车牌成功");
      getPageList(false); // 刷新列表
    })
    .catch((error) => {
      proxy.$msg.error("插入车牌失败：" + error.message);
    })
    .finally(() => {
      insertPlateNumberModal.confirmLoading = false;
      insertPlateNumberModal.visible = false;
    });
};

// 插入车牌取消
const handleInsertPlateNumberCancel = () => {
  insertPlateNumberModal.visible = false;
};
</script>
<style scoped></style>
